package com.hanbang.mrcm_merchant.else_module;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hanbang.mrcm_merchant.R;
import com.hanbang.mrcm_merchant.application.MyApplication;
import com.hanbang.mrcm_merchant.base.BaseActivity;
import com.hanbang.mrcm_merchant.myview.MyDialog;
import com.hanbang.mrcm_merchant.myview.MyDialog.MODE;
import com.hanbang.mrcm_merchant.myview.MyDialog.OnClickCallback;
import com.hanbang.mrcm_merchant.photo.ClipLayout;
import com.hanbang.mrcm_merchant.photo.ClipPhotoActivity;
import com.hanbang.mrcm_merchant.utils.EditHelper;
import com.hanbang.mrcm_merchant.utils.HttpInterfaces;
import com.hanbang.mrcm_merchant.utils.MyRequestCallBack;
import com.hanbang.mrcm_merchant.utils.MyToast;
import com.hanbang.mrcm_merchant.utils.SystemTools;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class RegisterActivity extends BaseActivity {
	// 拍完照存放的名称
		private String camera = "capture.jpg";
	private EditHelper editHelper = new EditHelper(this);
	private CheckBox checkBox;
	// 验证码按钮倒计时 总时长和间隔时长
	private long totalTime = 60000, intervalTime = 1000;
	private TextView authCodeButton,material;
	private ImageView merchant_logo;
	// logo本地路径
	private String logopath="";
	// 审核材料本地路径
	private String materialpath="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
		setOnClickListener();
	}

	/*
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		findViewById(R.id.user_register_button).setOnClickListener(
				onClickListener);
		authCodeButton.setOnClickListener(onClickListener);
		findViewById(R.id.protocol).setOnClickListener(onClickListener);
		findViewById(R.id.user_register_treaty).setOnClickListener(
				onClickListener);
		merchant_logo.setOnClickListener(onClickListener);
		material.setOnClickListener(onClickListener);
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.user_register_button:
				if (editHelper.check()) {
					if (!((EditText) findViewById(R.id.password))
							.getText()
							.toString()
							.trim()
							.equals(((EditText) findViewById(R.id.password2))
									.getText().toString().trim())) {
						MyToast.show(RegisterActivity.this, "两次密码不一致",
								Toast.LENGTH_LONG);
						break;
					}
					if (!checkBox.isChecked()) {
						MyToast.show(RegisterActivity.this, "请同意服务协议",
								Toast.LENGTH_LONG);
						break;
					}
					if (logopath.equals("")) {
						MyToast.show(RegisterActivity.this, "请选择商家logo",
								Toast.LENGTH_LONG);
						break;
					}
					if (material.getText().equals("")) {
						MyToast.show(RegisterActivity.this, "请选择审核材料",
								Toast.LENGTH_LONG);
						break;
					}
					register();
				}
				break;
			case R.id.user_register_auth_code_button:
				sendYZM();
				break;
			case R.id.user_register_treaty:
			case R.id.protocol:
				Intent intent = new Intent(RegisterActivity.this,
						RegisterProtocolActivity.class);
				startActivity(intent);
				break;
			case R.id.merchant_logo:
				 
				MyDialog dialog = new MyDialog(RegisterActivity.this,
						R.style.about_me_dialog, MODE.HEAD);
				dialog.setOnClickCallback(new OnClickCallback() {
					@Override
					public void onClick(MyDialog dialog, Object number,
							Object content) {
						// 拍照
						if ((Integer) number == 1) {
							File fDir = new File(MyApplication.picFilepath);
							if (fDir.exists() || fDir.mkdirs()) {
								File cameraFile = new File(fDir, camera);
								if (!cameraFile.exists()) {
									try {
										cameraFile.createNewFile();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
								Intent intent = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								intent.putExtra(MediaStore.EXTRA_OUTPUT,
										Uri.fromFile(cameraFile));
								startActivityForResult(intent, 998);
							}
							// 相册选择
						} else if ((Integer) number == 2) {
							// 获取相册
							Intent intent = new Intent();
							intent.setType("image/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
							intent.putExtra("return-data", true);
							startActivityForResult(intent, 999);
						}
					}
				});

				dialog.show();
				break;
			case R.id.audit_material:
				// 获取相册，选择logo
				Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
				fileintent.setType("*/*");
				fileintent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(Intent.createChooser(fileintent,
						"Select a File to Upload"), 2222);
				break;
			default:
				break;
			}
		}
	};

	/*
	 * 初始化view
	 */
	private void initView() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.top_bar_left_image));
		setTitle(findViewById(R.id.top_bar_title), "用户注册");
		material=((TextView)findViewById(R.id.audit_material));
		merchant_logo=((ImageView)findViewById(R.id.merchant_logo));
		checkBox = (CheckBox) findViewById(R.id.user_register_checkbox);
		authCodeButton = (TextView) findViewById(R.id.user_register_auth_code_button);
		editHelper.setEditText((EditText) findViewById(R.id.sellerlogin),
				(EditText) findViewById(R.id.password),
				(EditText) findViewById(R.id.password2),
				(EditText) findViewById(R.id.nice),
				(EditText) findViewById(R.id.merchant_address),
				(EditText) findViewById(R.id.phone),
				(EditText) findViewById(R.id.sms_yzm) 
				);
		editHelper.setHintText("请输入正确登录用户名", "请输入最少6位密码",
				"请输入最少6位确认密码","请输入商家名称", "请输入商家地址", "请正确输入手机号", "请输入短信验证码");
		editHelper.setHintMinNumber(1,6,6,1,1,11,1);

	}
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*
		 * 相册 resultCode: 正常返回-1 用户后退返回0
		 */

		if (requestCode == 999 && resultCode == -1) {
			Intent intent = new Intent(RegisterActivity.this,
					ClipPhotoActivity.class);
			Uri uri = data.getData();
			intent.putExtra("path",
					SystemTools.getPath(RegisterActivity.this, uri));
			configIntent(intent);
			startActivityForResult(intent, 1000);
			 
		}
		/*
		 * 相片裁剪界面发过来的
		 */
		if (requestCode == 1000 && resultCode == 1000) {
			logopath= data.getStringExtra("path");
			bitmapUtils.display(merchant_logo,
					logopath);
		}
		// 拍照返回的数据
		if (requestCode == 998 && resultCode == -1) {
			Intent intent = new Intent(RegisterActivity.this,
					ClipPhotoActivity.class);
			File fDir = new File(MyApplication.picFilepath);
			if (fDir.exists() || fDir.mkdirs()) {
				File cameraFile = new File(fDir, camera);
				if (cameraFile.exists()) {
					intent.putExtra("path", cameraFile.getPath());
					configIntent(intent);
					startActivityForResult(intent, 1000);
				} else {
					MyToast.show(RegisterActivity.this, "获取照片失败！",
							Toast.LENGTH_SHORT);
				}
			} else {
				MyToast.show(RegisterActivity.this, "获取照片失败！",
						Toast.LENGTH_SHORT);
			}
		}
//		  选择文件返回数据
		 if (resultCode == RESULT_OK&&requestCode==2222) {  
	            // Get the Uri of the selected file 
	            Uri uri = data.getData();
	              materialpath = SystemTools.getPath(this, uri);
	              int start=materialpath.lastIndexOf("/")+1;
	              int end=materialpath.length();
	              material.setText(materialpath.substring(start, end));
	        }     
		super.onActivityResult(requestCode, resultCode, data);
	};

	/*
	 * http://mrcm.hbung.com/tools/UserLogin.ashx?action=user_register&nickname=asa
	 * &mobile=19051196428&code=0532&password=123&againpassword=123 --注册
	 */
	private void register() throws IndexOutOfBoundsException {
		final ArrayList<String> res = editHelper.getText();
		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "seller_register");
		params.addBodyParameter("sellerlogin", res.get(0));
		params.addBodyParameter("password", res.get(1));
		params.addBodyParameter("againpassword", res.get(2));
		Log.e("jhohfasd", res.get(1)+"?+++?"+res.get(2));
		params.addBodyParameter("shop", res.get(3));
		params.addBodyParameter("shopaddress", res.get(4));
		params.addBodyParameter("mobile", res.get(5));
		params.addBodyParameter("code", res.get(6));
		File f = new File(logopath);
		if (f.exists()) {
			params.addBodyParameter("sellerlogo", f);
		}
		File file = new File(materialpath);
		if (file.exists()) {
			params.addBodyParameter("material", file);
		}
		httpUtils.send(HttpMethod.POST, HttpInterfaces.seller_register, params,
				new MyRequestCallBack<String>(this, "正在注册...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								Intent intent = new Intent();
								intent.putExtra("phone", res.get(5));
								intent.putExtra("password", res.get(1));
								setResult(999, intent);
								finish();
							} else {
								MyToast.show(RegisterActivity.this,
										json.getString("msg"),
										Toast.LENGTH_LONG);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(RegisterActivity.this, "注册失败",
									Toast.LENGTH_LONG);
						}
					}
				});
	}

	private void sendYZM() throws IndexOutOfBoundsException {
		final ArrayList<String> res = editHelper.getText();
		if (res.get(5) == null || res.get(5).equals("")
				|| res.get(5).length() < 11) {
			MyToast.show(RegisterActivity.this, "请正确输入手机号！", Toast.LENGTH_LONG);
			return;
		}
		Log.e("flfllflffl",  HttpInterfaces.seller_register
				  + "&mobile=" + res.get(5)+ "&type=1");
		httpUtils.send(HttpMethod.GET, HttpInterfaces.send_verify_sms_code
				  + "&mobile=" + res.get(5)+ "&type=1",
				new MyRequestCallBack<String>(this, "正在发送验证码...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								countDownTimer.start();
							}
							MyToast.show(RegisterActivity.this,
									json.getString("msg"), Toast.LENGTH_LONG);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
		@Override
		public void onFinish() {// 计时完毕时触发
			authCodeButton.setText("重新发送");
			authCodeButton.setEnabled(true);
			// authCodeButton.setClickable(true);
		}

		@Override
		public void onTick(long currentTime) {// 计时过程显示
			// authCodeButton.setClickable(false);
			authCodeButton.setEnabled(false);
			authCodeButton.setText(currentTime / 1000 + "秒");
		}
	};
	private void configIntent(Intent intent) {
		intent.putExtra("borderWidth", 2);
		intent.putExtra("clipPadding", 0);
		intent.putExtra("clipWidth", 1);
		intent.putExtra("clipHeight", 1);
		intent.putExtra("shared", ClipLayout.RECT);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
